﻿using System.Collections;
using System.Linq;
using Gp.Scripts.Data.Skills;
using Gp.Scripts.Core;
using QFramework;

namespace Gp.AI {
    [CreateNodeMenu("使用技能/单位能力")]
    public class UseAbilitySkillAINode : NormalAINode{
        public AbilitySkillEntityConfig ability;


        public override AINodeEntry NodeEntry() {
            return new UseAbilitySkillAINodeEntry(this);
        }
    }


    public class UseAbilitySkillAINodeEntry : NormalAINodeEntry<UseAbilitySkillAINode> {
        public UseAbilitySkillAINodeEntry(UseAbilitySkillAINode data) : base(data) { }
        private AbilitySkillEntity _skill;
        private SkillContext _context;
        protected override void PreCalculate() {
            // 有预设能力的情况
            // if (Data.ability != null) {
            //     var target = Unit.ComSkill.AbilitySkill.FirstOrDefault(x => x.EntityConfig == Data.ability);
            //     if (target == null || !target.CanPerform().Result()) return;
            //     var context = target.GetAIContext();
            //     if (context == null) return;
            //
            //     _context = context;
            //     _skill = target;
            //     return;
            // }
            
            
            // 智能选择
            var item = Unit.ComSkill.AbilitySkill
                .Where(s => s.CanSelect().Result() && s.GetAIContext() != null)
                .ToList().GetRandomItem();

            if (item == null) return;
            
            _skill = item;
            _context = item.GetAIContext();
        }


        protected override AIActionArgs GetActionInfo() {
            return AIActionArgs.Build(_skill);
        }


        
        public override IEnumerator OnExecute() {
            yield return _skill.AIExecute(_context);
        }
        
        public override bool ShouldPerform() {
            return _skill != null && _context != null;
        }
    }
}